package com.rxy.api;

import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

public class CreateSession implements Watcher {

    // 计数工具类，让线程处于等待阻塞，主要不让main方法结束
    private static CountDownLatch countDownLatch = new CountDownLatch(1);

    public static void main(String[] args) throws IOException, InterruptedException {
        /**
         * 客户端可以通过创建一个zk实例来连接zk服务器
         * new Zookeeper(connectString,sesssionTimeOut,Watcher)
         * connectString: 连接地址，IP：端⼝
         * sesssionTimeOut：会话超时时间，单位毫秒
         * Watcher：监听器(当特定事件触发监听时，zk会通过watcher通知到客户端)
         */
        ZooKeeper zooKeeper = new ZooKeeper("192.168.31.247:2181",
                5000, new CreateSession());
        System.out.println(zooKeeper.getState());
        // 阻塞当前线程
        countDownLatch.await();
        // 客户端与服务端会话真正建立了
        System.out.println("====Client Connected to zookeeper====");
    }

    /**
     * 回调方法，该方法负责处理来自Zookeeper服务端的watcher通知
     */
    @Override
    public void process(WatchedEvent watchedEvent) {
        // 当连接创建了，服务端发送给客户端SyncConnected事件
        if (watchedEvent.getState() == Event.KeeperState.SyncConnected) {
            System.out.println("process方法执行了...");
            // 解除主程序在countDownLatch上的等待阻塞
            countDownLatch.countDown();
        }
    }
}
